#include "drawing.h"

#include <assert.h>
#include <stdlib.h>
#include <time.h>

#include "global.h"
#include "palette.h"

void fill_3d_box(SDL_Surface* sf, SDL_Rect* r, Relief relief)
{
	assert(sf);
	assert(r);

	srand(time(NULL));

	// background
	SDL_FillRect(sf, &(SDL_Rect){r->x+2,r->y+2,r->w-4,r->h-4}, STONE1);

	// lock surface
	if(SDL_MUSTLOCK(screen))
		if(SDL_LockSurface(screen) == -1)
			ui_error("Error locking surface.");

	// background texture
	int x, y;
	for(x=(r->x+2); x<(r->x+r->w-4); x++)
		for(y=(r->y+2); y<(r->y+r->h-4); y++)
			if(rand() % 5 < 2)
				SET_PX(sf, x, y, STONE2);

	// get border colors
	uint8_t c1, c2, c3, c4;
	switch(relief)
	{
		case LOWER:
			c1 = STONE1_SH;
			c2 = STONE2_SH;
			c3 = STONE1_LG;
			c4 = STONE2_LG;
			break;
		case PLAIN:
			c1 = c3 = STONE1;
			c2 = c4 = STONE2;
			break;
		case UPPER:
			c1 = STONE1_LG;
			c2 = STONE2_LG;
			c3 = STONE1_SH;
			c4 = STONE2_SH;
			break;
		default:
			abort();
	}

	// borders
	for(x=(r->x+1); x<(r->x+r->w-1); x++)
		SET_PX(sf, x, r->y, ((rand() % 5 < 2) ? c1 : c2));
	for(x=(r->x); x<(r->x+r->w); x++)
		SET_PX(sf, x, (r->y+1), ((rand() % 5 < 2) ? c1 : c2));
	for(y=(r->y+1); y<(r->y+r->h-1); y++)
		SET_PX(sf, r->x, y, ((rand() % 5 < 2) ? c1 : c2));
	for(y=(r->y); y<(r->y+r->h); y++)
		SET_PX(sf, (r->x+1), y, ((rand() % 5 < 2) ? c1 : c2));
	for(x=(r->x+2); x<(r->x+r->w-1); x++)
		SET_PX(sf, x, (r->y+r->h-1), ((rand() % 5 < 2) ? c3 : c4));
	for(x=(r->x+2); x<(r->x+r->w); x++)
		SET_PX(sf, x, (r->y+r->h-2), ((rand() % 5 < 2) ? c3 : c4));
	for(y=(r->y+2); y<(r->y+r->h-1); y++)
		SET_PX(sf, (r->x+r->w-1), y, ((rand() % 5 < 2) ? c3 : c4));
	for(y=(r->y+2); y<(r->y+r->h); y++)
		SET_PX(sf, (r->x+r->w-2), y, ((rand() % 5 < 2) ? c3 : c4));

	// unlock surface
	if(SDL_MUSTLOCK(screen))
		SDL_UnlockSurface(screen);
}
